package com.td.erhome.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.td.erhome.App;
import com.td.erhome.models.BaseBean;
import com.td.erhome.models.PayRey;
import com.td.erhome.net.Api;
import com.td.erhome.net.BaseSubscriber;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.util.HashMap;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/2/15 0015.
 */

public class PayUtils {

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private Activity mActivity;
    private String mSn;
    private String mYear = "";
    private double mAnnualFee;
    private double mTotalFee;
    private int mAmount = 0;


    public PayUtils(Activity activity) {
        mActivity = activity;
    }
    //支付定金
    public  void getPrePay(final HashMap<String,Object> params){

        Api.getRetrofit().sellHousePublish(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean<PayRey>>(mActivity){
                    @Override
                    public void onNext(BaseBean<PayRey> payReyBaseBean) {
                        super.onNext(payReyBaseBean);

                        if (params.get("pay_type").equals("wechatpay"))
                            getPayReq(payReyBaseBean.getData());

                        if (params.get("pay_type").equals("alipay"))
                            payV2(payReyBaseBean.getData().alipay_config);

                    }
                });
    }


     //支付获取电话
    public  void getSellerInfo(final HashMap<String,Object> params){

        Api.getRetrofit().getSellerInfo(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean<PayRey>>(mActivity){
                    @Override
                    public void onNext(BaseBean<PayRey> payReyBaseBean) {
                        super.onNext(payReyBaseBean);

                        if (params.get("pay_type").equals("wechatpay"))
                            getPayReq(payReyBaseBean.getData());

                        if (params.get("pay_type").equals("alipay"))
                            payV2(payReyBaseBean.getData().alipay_config);

                    }
                });
    }


    /**
     * 微信支付
     */
    public  void getPayReq(PayRey data) {
        PayReq mPayReq = new PayReq();
        mPayReq.appId = data.wechat_pay_config.appid;// AppId
        mPayReq.partnerId = data.wechat_pay_config.partnerid;// 微信支付分配的商户号
        mPayReq.prepayId = data.wechat_pay_config.prepayid;// 支付订单Id
        mPayReq.packageValue = "Sign=WXPay";// 扩展字段，暂填写固定值Sign=WXPay
        mPayReq.nonceStr =data.wechat_pay_config.noncestr;// 随机数字符串
        mPayReq.timeStamp = data.wechat_pay_config.timestamp; // 时间戳
        mPayReq.sign = data.wechat_pay_config.sign;
        App.getInstance().mIWXAPI.sendReq(mPayReq);
    }

    /**
    * 支付宝支付
    *
    */
    public  void payV2( final String mOrderInfo ) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(mOrderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝支付结果回调
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            Log.i("56656654",msg.toString());

            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                     //   Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT).show();

                        RxBus.getInstance().post(ConstUtils.FINISH_CON);


                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                       // Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(mActivity,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(mActivity,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

}
